package com.wzu.servlet;

import com.wzu.pojo.BorrowRecord;
import com.wzu.service.BorrowRecordService;
import com.wzu.service.BorrowRecordServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 处理借阅记录列表请求的Servlet
 */
@WebServlet("/borrowRecordList")
public class BorrowRecordServlet extends HttpServlet {
    // 业务逻辑服务层对象
    private BorrowRecordService borrowRecordService = new BorrowRecordServiceImpl();

    /**
     * 处理GET请求，返回借阅记录列表页面
     *
     * @param request  请求对象，包含客户端的请求信息
     * @param response 响应对象，用于向客户端发送响应
     * @throws ServletException 如果Servlet遇到异常
     * @throws IOException      如果发生输入或输出异常
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型和字符编码
        response.setContentType("text/html;charset=UTF-8");
        // 获取响应输出流，用于输出HTML内容
        PrintWriter out = response.getWriter();

        // 调用服务层方法获取所有借阅记录信息
        List<BorrowRecord> recordList = borrowRecordService.getAllBorrowRecords();

        // 输出HTML开始部分
        out.println("<html><body>");
        out.println("<h2>借阅记录列表</h2>");
        // 输出借阅记录列表表格的样式和表头
        out.println("<table border='1'>");
        out.println("<tr><th>记录ID</th><th>用户ID</th><th>图书ID</th><th>借阅日期</th><th>归还日期</th><th>是否归还</th></tr>");
        // 遍历借阅记录列表，输出每条借阅记录的信息
        for (BorrowRecord record : recordList) {
            out.println("<tr>");
            out.println("<td>" + record.getRecord_id() + "</td>");
            out.println("<td>" + record.getUser_id() + "</td>");
            out.println("<td>" + record.getBook_id() + "</td>");
            out.println("<td>" + record.getBorrow_date() + "</td>");
            out.println("<td>" + record.getReturn_date() + "</td>");
            out.println("<td>" + (record.isIs_returned() ? "是" : "否") + "</td>");
            out.println("</tr>");
        }
        // 输出表格和HTML结束部分
        out.println("</table>");
        out.println("</body></html>");
    }
}